﻿using System;
using System.Collections.Generic;
using System.Linq;
using Medianamik.Core;
using Telerik.Web.UI;

namespace Medianamik.UI.Controls
{
    public class WebPageComboTree : ComboTree
    {
        private List<Node> _rootNodes;

        protected override List<Node> RootNodes
        {
            get
            {
                if (_rootNodes == null)
                {
                    _rootNodes = NodeManager.GetNodesByType(MedianamikTypes.Module);

                    _rootNodes.RemoveAll(m => m.ChildNodeCount < 1 || NodeManager.CountChildNodesByType(m,
                        MedianamikTypes.BaseWebType, true) < 1);

                    _rootNodes.Sort((n1, n2) => n1.LongPosition.CompareTo(n2.LongPosition));
                    _rootNodes.RemoveAll(n => n.NodeTypeID.Equals(MedianamikTypes.MedianamikSyndication));
                    _rootNodes.RemoveAll(FilterNode);
                }
                return _rootNodes;
            }
        }

        protected override void NodeExpand(RadTreeNode parentNode)
        {
            var childs = NodeManager.GetChildNodes(new Guid(parentNode.Value))
                .Where(n => !n.NodeType.IsSystem && (n.NodeType.IsChildOf(MedianamikTypes.BaseWebType) ||
                    NodeManager.CountChildNodesByType(n, MedianamikTypes.BaseWebType, false) > 0)).ToList();

            childs.Sort((n1, n2) => n1.LongPosition.CompareTo(n2.LongPosition));
            childs.RemoveAll(n => n.NodeTypeID.Equals(MedianamikTypes.MedianamikSyndication));
            childs.RemoveAll(FilterNode);

            foreach (var child in childs)
            {
                var nd = new RadTreeNode(child.DisplayName, child.ID.ToString());

                if (child.HasChildren)
                    nd.ExpandMode = TreeNodeExpandMode.ServerSideCallBack;

                if (!OptionNodeIds.Contains(child.ID) ||
                    (IsSyndication && !ParentNode.LegitimateChildTypes.Any(t => t.ID.Equals(child.NodeTypeID))))
                {
                    nd.Category = "Disabled";
                    nd.CssClass += " rtDisabled";
                    nd.HoveredCssClass = "rtDisabled";
                    nd.SelectedCssClass = "rtDisabled";
                }

                parentNode.Nodes.Add(nd);
            }

            parentNode.ExpandMode = TreeNodeExpandMode.ClientSide;
            parentNode.Expanded = true;
        }
    }
}